<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix"><span>更改登录密码</span><br /></div>
    <!-- 内容区放表单 -->
    <el-form label-width="110px" ref="from" :model="pass" :rules="rules">
      <!-- 表单中的每一行，叫做 el-form-item -->
      <el-form-item label="原密码" prop="old_pwd">
        <el-input v-model="pass.old_pwd"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input v-model="pass.new_pwd"></el-input>
      </el-form-item>
      <el-form-item label="请输入新密码" prop="re_pwd">
        <el-input v-model="pass.re_pwd"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="send">修改密码</el-button>
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { updatedPwdAPI } from '@/api/user'
export default {
  data() {
    // 自定义规则
    const newPwd = (rule, value, callback) => {
      if (value === this.pass.old_pwd) {
        callback(new Error('两次密码一样'))
      } else {
        callback()
      }
    }
    const rePwd = (rule, value, callback) => {
      if (value === this.pass.new_pwd) {
        callback()
      } else {
        callback(new Error('两次密码不一致'))
      }
    }

    return {
      pass: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      rules: {
        old_pwd: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        new_pwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码长度在 6 到 15 个字符', trigger: 'blur' },
          { validator: newPwd, trigger: 'blur' }
        ],
        re_pwd: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码长度在 6 到 15 个字符', trigger: 'blur' },
          { validator: rePwd, trigger: 'blur' }
        ]
      }
    }
  },

  methods: {
    send() {
      this.$refs.from.validate(async valid => {
        const { data: res } = await updatedPwdAPI(this.pass)
        if (res.code === 0) {
          this.$message.success(res.message)
          this.$refs.from.resetFields() // 重置表单

          // 跟登录一样，清除state里面的数据，跳转到登录界面
          this.$store.commit('user/updatedToken', '')
          this.$store.commit('user/updatedget', {})
          this.$router.push('/login')
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>

<style scoped>
.el-card {
  font-size: 13px;
}

.el-form {
  width: 500px;
}
</style>
